/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
***********************************************/
package models

import (
	"github.com/astaxie/beego/orm"
	"errors"
)

type ManageAdminUser struct {
	Id         int
	LoginName  string
	RealName   string
	Password   string
	Phone      string
	Email      string
	Salt       string
	LastLogin  int64
	LastIp     string
	Status     int
	CreateId   int
	UpdateId   int
	CreateTime int64
	UpdateTime int64
	Explain	 string
}



func (a *ManageAdminUser) TableName() string {
	return TableName("ManageAdminUser")
}

func ManageAdminAdd(a *ManageAdminUser) (int64, error) {
	return orm.NewOrm().Insert(a)
}

func  ManageAdminGetByName(loginName string) (*ManageAdminUser, error) {

	o := orm.NewOrm()
	user := ManageAdminUser{LoginName: loginName}

	err := o.Read(&user,"LoginName")

	if err == orm.ErrNoRows {
 	   return &user, err
	} else if err == orm.ErrMissPK {
     	return &user, err
	} else {
        return &user, err
    }
	return &user, errors.New("无结果！")
}

func  ManageAdminGetList(page, pageSize int, filters ...interface{}) ([]*ManageAdminUser, int64) {
	offset := (page - 1) * pageSize
	list := make([]*ManageAdminUser, 0)
	query := orm.NewOrm().QueryTable(TableName("ManageAdminUser"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)

	return list, total
}

func  ManageAdminGetById(id int) (*ManageAdminUser, error) {

	o := orm.NewOrm()
	user := ManageAdminUser{Id: id}

	err := o.Read(&user,"Id")

	if err == orm.ErrNoRows {
 	   return &user, err
	} else if err == orm.ErrMissPK {  
     	return &user, err
	} else {
        return &user, err
   	}
	return &user, errors.New("无结果！")
}

func (a *ManageAdminUser) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}
func  UserLoginNameExist(loginName string) bool{
	o := orm.NewOrm()
	o.Using("default")
	Gettable := o.QueryTable(TableName("ManageAdminUser"));
	return Gettable.Filter("LoginName", loginName).Exist()
}


// func RoleAuthDelete(id int) (int64, error) {
// 	query := orm.NewOrm().QueryTable(TableName("role_auth"))
// 	return query.Filter("role_id", id).Delete()
// }

// func RoleAuthMultiAdd(ras []*RoleAuth) (n int, err error) {
// 	query := orm.NewOrm().QueryTable(TableName("role_auth"))
// 	i, _ := query.PrepareInsert()
// 	for _, ra := range ras {
// 		_, err := i.Insert(ra)
// 		if err == nil {
// 			n = n + 1
// 		}
// 	}
// 	i.Close() // 别忘记关闭 statement
// 	return n, err
// }
